// ==UserScript==
// @name         high购管理页加强
// @namespace    https://gitee.com/vbox007/Tampermonkey/raw/master/
// @version      1.0.0.8
// @description  为high管理网页增加最为基础的操作
// @author       vbox007
// @icon         
// @match        http://chain.whzb.com:8081/
// @connect      image.whzb.com
// @grant        GM_xmlhttpRequest
// @require      https://cdn.bootcdn.net/ajax/libs/xlsx/0.16.9/xlsx.full.min.js
// @require      https://cdn.bootcdn.net/ajax/libs/qrcodejs/1.0.0/qrcode.js
// ==/UserScript==

(function () {
    'use strict';
    // if(location.href != "http://chain.whzb.com:8081/#/home/grouponPickingOrder-request"){
    //     return;
    // }
    // if(localStorage.token == undefined){
    //     return
    // }
    var $ = function (x) {
        return document.getElementById(x);
    };
    var i, j, read_row, commodity, v_order_list, create_print_list, Chief_order, jdllt;
    jdllt = {
        'zbccmd_1004': 'http://g3v.cn/5uqdZ',
        'zbccmd_1007': 'http://g3v.cn/5pLaQ',
        'zbccmd_1010': 'http://g3v.cn/65fJ3',
        'zbccmd_1077': 'http://g3v.cn/60DiO',
        'zbccmd_1093': 'http://g3v.cn/5WowH',
        'zbccmd_1100': 'http://g3v.cn/5RJty',
        'zbccmd_1104': 'http://g3v.cn/5N4qp',
        'zbccmd_1109': 'http://g3v.cn/5Ipng',
        'zbccmd_1111': 'http://g3v.cn/5DKk7',
        'zbccmd_1140': 'http://g3v.cn/5z5gY',
        'zbccmd_1203': 'http://g3v.cn/5uqdP',
        'zbccmd_1208': 'http://g3v.cn/5pLaG',
        'zbccmd_1216': 'http://g3v.cn/65fKv',
        'zbccmd_1217': 'http://g3v.cn/60DiE',
        'zbccmd_1228': 'http://g3v.cn/5Wowx',
        'zbccmd_1230': 'http://g3v.cn/5uqcx'
    };
    var create_print_page = function () {
        i = 0;
        read_row = 0;
        var fixed_html = [
            '<p><span style="text-align:center;display:block;font-weight:bold;font-size:24px">high购批次单</span><br/>批次单号：<br/>',
            '<br/>创建时间：',
            '<br/>订单总数(单)：',
            '<span style="text-align:center;display:block;font-size:12px">',
            '号单</span><br/><span style="font-weight:bold;font-size:32px">',
            '<br/></span><br/>',
            '<div class="adqr" style="width:168px;"></div><br/><span style="text-align:center;display:block;">订单号：',
            '<br/>----------------------------</span>客户姓名：',
            '<br/>联系电话：',
            '<span style="text-align:center;display:block;">----------------------------</span>品名&emsp;&emsp;&emsp;国标码&emsp;&emsp;&emsp;数量<br/>',
            '<span style="text-align:center;display:block;">----------------------------</span>商品品数：',
            '&emsp;&emsp;商品件数：',
            '<span style="text-align:center;display:block;">----------------------------</span>自提点名称：',
            '<br/>自提点联系人：',
            '<br/>自提点联系电话：',
            '<br/><br/><span style="text-align:center;display:block;font-size:12px">############裁剪线############</span><br/><br/><br/>'
        ]
        var innh = '<div id="ddbarcode" class="bc-left">';
        for (i = 0; i < create_print_list.length; i++) {
            innh += fixed_html[0] + create_print_list[i].Total.BatchNum;
            innh += fixed_html[1] + create_print_list[i].Total.CreationTime;
            innh += fixed_html[2] + create_print_list[i].Total.OrderQuantity;
            innh += fixed_html[15];
            // innh+='<br/>'.repeat(5);
            for (j = 0; j < create_print_list[i].orders.length; j++) {
                innh += fixed_html[3] + (j + 1);
                innh += fixed_html[4] + create_print_list[i].orders[j].GuestPhone.substr(0, 3);
                innh += 'high' + create_print_list[i].orders[j].GuestPhone.substr(7, 11);
                innh += fixed_html[5] + create_print_list[i].orders[j].Time;
                innh += fixed_html[6] + create_print_list[i].orders[j].Order;
                innh += fixed_html[7] + create_print_list[i].orders[j].GuestName;
                innh += fixed_html[8] + create_print_list[i].orders[j].GuestPhone;
                innh += fixed_html[9];
                for (read_row = 0; read_row < create_print_list[i].orders[j].commodity.length; read_row++) {
                    innh += create_print_list[i].orders[j].commodity[read_row].name + '<br/>';
                    innh += create_print_list[i].orders[j].commodity[read_row].code + '&emsp;'.repeat(4);
                    if (create_print_list[i].orders[j].commodity[read_row].num == 1) {
                        innh += '&emsp;x1<br/>';
                    } else {
                        innh += '<span style="font-weight:bold;font-size:32px">×' + create_print_list[i].orders[j].commodity[read_row].num + '</span><br/>';
                    }
                }
                innh += fixed_html[10] + create_print_list[i].orders[j].num[0];
                innh += fixed_html[11] + create_print_list[i].orders[j].num[1];
                innh += fixed_html[12] + create_print_list[i].Total.PointName;
                innh += fixed_html[13] + create_print_list[i].Total.ChiefName;
                innh += fixed_html[14] + create_print_list[i].Total.ChiefPhone;
                innh += fixed_html[15];
            }
        }
        innh += '</div>';
        return innh;
    };
    var open_print_page = function () {
        const newTab = window.open('', '_blank', '');
        newTab.document.open('text/html', 'replace');
        newTab.opener = null
        newTab.document.write(create_print_page());
        newTab.document.head.innerHTML = '<meta http-equiv="Content-Type"content="text/html;charset=gb2312"><title>越秀high购面单打印</title><style>div{width:240px;margin:0 auto;text-align:center}.bc-left{width:240px;height:168px;margin:0 auto;text-align:left}</style>'
        // var link = document.createElement('link');
        // link.type = 'image/x-icon';
        // link.rel = 'shortcut icon';
        // link.href = '';
        // newTab.document.getElementsByTagName('head')[0].appendChild(link);
        var adqr = newTab.document.getElementsByClassName('adqr');
        for (i = 0; i < adqr.length; i++) {
            var qrm = new QRCode(adqr[i], { width: 168, height: 168 });//初始化二维码要用的div
            qrm.makeCode(jdllt[localStorage.loginName] || 'http://g3v.cn/5uqdP');
        }
        newTab.document.close();
        setTimeout(function () { newTab.window.print() }, 1024);
    }
    var get_printpage = (function (printono, pall) {
        if (printono < v_order_list.length) {
            fetch("http://chain.whzb.com:8081/base/rest/m-groupon/pickingOrder-request/downloadPickingOrder", {
                "headers": {
                    "accept": "application/json, text/plain, */*",
                    "accept-language": "zh-CN,zh;q=0.9",
                    "access-token": localStorage.token,
                    "content-type": "application/x-www-form-urlencoded",
                    "sign-value": "dev"
                },
                "referrer": "http://chain.whzb.com:8081/",
                "referrerPolicy": "strict-origin-when-cross-origin",
                "body": "pickingOrderNo=" + v_order_list[printono],
                "method": "POST",
                "mode": "cors",
                "credentials": "omit"
            }).then(res => res.json()).then(pobj => {
                var url = pobj.data.file.accessUrl;
                url = url.replace('https://', 'http://');
                GM_xmlhttpRequest({
                    method: "get",
                    url: url,
                    responseType: 'arraybuffer',
                    onload: function (res) {
                        try {
                            var data = new Uint8Array(res.response)
                            var workbook = XLSX.read(data, { type: 'array' });
                            Chief_order = { "Total": {}, "orders": [] }
                            Chief_order.Total.BatchNum = workbook.Sheets.批次单合计.B3.w
                            Chief_order.Total.CreationTime = workbook.Sheets.批次单合计.D3.w;
                            Chief_order.Total.EstimatedTime = workbook.Sheets.批次单合计.B5.w;
                            Chief_order.Total.PointCode = workbook.Sheets.批次单合计.B9.w;
                            Chief_order.Total.PointName = workbook.Sheets.批次单合计.D9.w;
                            Chief_order.Total.ChiefName = workbook.Sheets.批次单合计.B10.w;
                            Chief_order.Total.ChiefPhone = workbook.Sheets.批次单合计.D10.w;
                            Chief_order.Total.OrderQuantity = workbook.Sheets.订单详情.B4.v;
                            read_row = 7;
                            for (i = 0; i < Chief_order.Total.OrderQuantity; i++) {
                                Chief_order.orders[i] = {};
                                Chief_order.orders[i].Order = workbook.Sheets.订单详情['A' + read_row].w.split(":")[1];
                                read_row += 2;
                                Chief_order.orders[i].Time = workbook.Sheets.订单详情['B' + read_row].w;
                                read_row += 1;
                                Chief_order.orders[i].GuestName = workbook.Sheets.订单详情['B' + read_row].w;
                                Chief_order.orders[i].GuestPhone = workbook.Sheets.订单详情['D' + read_row].w;
                                read_row += 5;
                                commodity = [];
                                Chief_order.orders[i].num = [0, 0]
                                while (workbook.Sheets.订单详情["B" + read_row] != undefined) {
                                    commodity[commodity.length] = {};
                                    commodity[commodity.length - 1].name = workbook.Sheets.订单详情['A' + read_row].w.split("：")[1];
                                    commodity[commodity.length - 1].code = workbook.Sheets.订单详情['B' + read_row].w;
                                    commodity[commodity.length - 1].num = workbook.Sheets.订单详情['E' + read_row].v;
                                    Chief_order.orders[i].num[0] += 1;
                                    Chief_order.orders[i].num[1] += commodity[commodity.length - 1].num;
                                    read_row += 1;
                                }
                                Chief_order.orders[i].commodity = commodity;
                                read_row += 5;
                            }
                            create_print_list[create_print_list.length] = Chief_order;
                            $(pall ? 'okprinta' : 'okprint').innerText = '读取中（' + printono + '/' + v_order_list.length + '）';
                            get_printpage(printono + 1, pall);
                        } catch (error) {
                            console.log('*');
                            console.log(error.message);
                            console.log('*');
                        }
                    },
                    onerror: function (err) {
                        console.log('*');
                        console.log(err);
                        console.log('*');
                    }
                });
            });
        } else {
            console.log(create_print_list);
            $(pall ? 'okprinta' : 'okprint').innerText = pall ? '打印本页所有订单' : '打印本页未发货订单';
            open_print_page();
        }
    });
    var deliverorder = (function (pickono) {
        if (pickono < v_order_list.length) {
            fetch("http://chain.whzb.com:8081/base/rest/m-groupon/pickingOrder-request/confirmPickingOrder", {
                "headers": {
                    "accept": "application/json, text/plain, */*",
                    "accept-language": "zh-CN,zh;q=0.9",
                    "access-token": localStorage.token,
                    "content-type": "application/x-www-form-urlencoded",
                    "sign-value": "dev"
                },
                "referrer": "http://chain.whzb.com:8081/",
                "referrerPolicy": "strict-origin-when-cross-origin",
                "body": "pickingOrderNo=" + v_order_list[pickono],
                "method": "POST",
                "mode": "cors",
                "credentials": "omit"
            }).then(res => {
                deliverorder(pickono + 1);
            });
        } else {
            document.getElementsByClassName('searchBtn flex justifyCenter alignCenter')[0].firstChild.click();
        }
    });
    var deliverall = function () {
        if (confirm('确认要进行一键发货吗？')) {
            v_order_list = [];
            var cnetc = document.getElementsByClassName('el-table__header-wrapper')[0].firstElementChild.rows[0].cells
            for (i = 0; i < cnetc.length; i++) {
                if(cnetc[i].innerText.indexOf('状态') >= 0) {
                    break;
                }
            }
            var statusColumn = i;
            for (i = 0; i < cnetc.length; i++) {
                if(cnetc[i].innerText.indexOf('批次单号') >= 0) {
                    break;
                }
            }
            cnetc = document.getElementsByClassName(cnetc[i].classList[0] + ' is-left');
            for (i = 0; i < cnetc.length; i++) {
                if (cnetc[i].parentNode.children[statusColumn].innerText == '已生成' && v_order_list.indexOf(cnetc[i].innerText) < 0) {
                    v_order_list[v_order_list.length] = cnetc[i].innerText;
                }
            }
            deliverorder(0);
        }
    };
    var printall = function () {
        v_order_list = [];
        var cnetc = document.getElementsByClassName('el-table_1_column_10 is-left ');
        for (i = 0; i < cnetc.length; i++) {
            if (v_order_list.indexOf(cnetc[i].innerText) < 0) {
                v_order_list[v_order_list.length] = cnetc[i].innerText;
            }
        }
        create_print_list = [];
        $('okprinta').innerText = '读取中（0/' + v_order_list.length + '）';
        get_printpage(0, 1);
    };
    var printo = function () {
        v_order_list = [];
        var cnetc = document.getElementsByClassName('el-table_1_column_10 is-left ');
        for (i = 0; i < cnetc.length; i++) {
            if (cnetc[i].parentNode.children[8].innerText == '已生成' && v_order_list.indexOf(cnetc[i].innerText) < 0) {
                v_order_list[v_order_list.length] = cnetc[i].innerText;
            }
        }
        create_print_list = [];
        $('okprint').innerText = '读取中（0/' + v_order_list.length + '）';
        get_printpage(0, 0);
    };
    var wait_high_ev = function () {
        var btn_ft = document.getElementsByClassName('btnGroupsCom');
        if (btn_ft.length > 0) {
            btn_ft[0].innerHTML = '<button id="okdeliver" type="button" class="btn syncBtn">本页一键发货</button>' + btn_ft[0].innerHTML;
            btn_ft[0].innerHTML = '<button id="okprinta" type="button" class="btn syncBtn" style="Width:auto">打印本页所有订单</button>' + btn_ft[0].innerHTML;
            btn_ft[0].innerHTML = '<button id="okprint" type="button" class="btn syncBtn" style="Width:auto">打印本页未发货订单</button>' + btn_ft[0].innerHTML;
            $('okdeliver').style.width = $('okdeliver').clientWidth + 'px'
            $('okdeliver').onclick = (function (ev) {
                deliverall();
                return false;
            });
            $('okprinta').style.width = $('okprinta').clientWidth + 20 + 'px'
            $('okprinta').onclick = (function (ev) {
                printall();
                return false;
            });
            $('okprint').style.width = $('okprint').clientWidth + 20 + 'px'
            $('okprint').onclick = (function (ev) {
                printo();
                return false;
            });
        } else {
            setTimeout(wait_high_ev, 128);
        }
    }
    wait_high_ev();
    // Your code here...
})();